<?php

namespace app\api\service;

use app\api\model\AdminModel;
use app\api\model\TeamModel;
use think\Db;
use think\Request;
use think\Validate;

class TeamService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 添加团队
     */
    public function addTeam($params)
    {
        $Validate = new Validate([
            'title' => 'require',
            'remark' => 'require',
            'charge' => 'require',
            'chargePhone' => 'require',
            'status' => 'require',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $saveData = [
            'title' => $params['title'],
            'remark' => $params['remark'],
            'charge' => $params['charge'],
            'chargePhone' => $params['chargePhone'],
            'status' => $params['status'],
        ];
        //获取当前账号所属团队
        $teamPid = AdminModel::getInstance()->value([
            'id' => ['eq', $this->uid]
        ], 'team');
        $saveData['pid'] = $teamPid;

        LogService::getInstance()->writeSysLog([
            'operation' => '/api/admin/changeTeam',
            'title' => !empty($params['id']) ? '编辑' : '添加',
            'content' => $params,
        ]);
        if (empty($params['status']) && !empty($params['id']))
        {
            Db::name('admin')->where([
                'team' => ['eq', $params['id']]
            ])->update([
                'status' => 0
            ]);
        }
        if (!empty($params['id']))
        {
            $saveData['u_time'] = datetime(time(), 'Y-m-d H:i:s');
            $res = TeamModel::getInstance()->update([
                'id' => ['eq', $params['id']]
            ], $saveData);
            return $res ? $params['id'] : $res;
        }
        $saveData['c_time'] = datetime(time(), 'Y-m-d H:i:s');
        $res = TeamModel::getInstance()->insert($saveData);
        return $res;
    }

    /**
     * 获取指定团队信息
     */
    public function getTeamInfo($params)
    {
        $Validate = new Validate([
            'id' => 'require'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $info = TeamModel::getInstance()->find([
            'id' => ['eq', $params['id']]
        ]);
        return $info;
    }

    /**
     * 获取账号团队及其下属团队
     */
    public function getTeam($params)
    {
        //超管获取 需增加 id为0的团队
        $teamIds = self::getTeamIds();
        $where = [
            'id' => ['in', $teamIds],
            'status' => ['eq', 1]
        ];
        if (isset($params['title']))
        {
            $where['title'] = ['LIKE', '%'.$params['title'].'%'];
        }
        $teamList = TeamModel::getInstance()->select($where, 'id,title', 0, 10000);
        return $teamList;
    }

    /**
     * 获取团队列表
     */
    public function getTeamList($params)
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 15);
        $start = ($page - 1) * $limit;

        $where = [];
        $teamIds = self::getTeamIds();
        $where['id'] = ['in', $teamIds];
        if (isset($params['title']))
        {
            $where['title'] = ['LIKE', '%'.$params['title'].'%'];
        }
        if (isset($params['remark']))
        {
            $where['remark'] = ['LIKE', '%'.$params['remark'].'%'];
        }
        if (isset($params['charge']))
        {
            $where['charge'] = ['LIKE', '%'.$params['charge'].'%'];
        }
        if (isset($params['chargePhone']))
        {
            $where['chargePhone'] = ['eq', $params['chargePhone']];
        }
        if (isset($params['status']))
        {
            $where['status'] = ['eq', $params['status']];
        }

        $total = TeamModel::getInstance()->count($where);
        $list = TeamModel::getInstance()->select($where, '*', $start, $limit);
        return [
            'total' => $total,
            'list' => $list
        ];
    }

    /**
     * 获取指定团队及其下级团队
     */
    public function getTeamIds()
    {
        $teamList = TeamModel::getInstance()->select([], '*', 0, 10000);
        $pid = AdminModel::getInstance()->value([
            'id' => ['eq', $this->uid]
        ], 'team');
        $teamTree = $this->uid == 1 ? array_column($teamList, 'id') : self::getTeamTree($teamList, $pid);
        $teamTree[] = $pid;
        return $teamTree;
    }

    public function getTeamTree($data, $pid = 0)
    {
        $ids = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                $ids[] = $v['id'];
                unset($data[$k]);
                $child = self::getTeamTree($data, $v['id']);
                if (!empty($child))
                {
                    foreach ($child as $item)
                    {
                        $ids[] = $item;
                    }
                }
            }
        }
        return $ids;



        /*$teamTree = [];
        foreach ($data as $k => $v)
        {
            if ($v['pid'] == $pid)
            {
                $teamTree[] = $v['id'];
                $child = self::getTeamTree($data, $v['id']);
                if (!empty($child))
                {
                    foreach ($child as $item)
                    {
                        $teamTree[] = $item;
                    }
                }
            }
        }
        return $teamTree;*/
    }
}